package activities;

import java.util.List;

import org.apache.http.ParseException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import helper.GetMyScheduleHelper;
import helper.HttpHelper;

import com.matchcalendar.R;

import dataFormat.CalendarTextData;

import factories.CalendarTextDataFactory;
import fragments.SetFixedScheduleFragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

public class SetFixedScheduleActivity extends FragmentActivity {
	private SetFixedScheduleFragment setFixedScheduleFragment = new SetFixedScheduleFragment(true, null);
	private Button buttonPrevious, buttonDone;
	public final int SET_SCHEDULE_REQUEST_CODE = 0;
	private final int MODIFY_SCHEDULE_REQUEST_CODE = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.custom_set_fixed_schedule);
		findView();
		setListenerOrAdapter();
		getSupportFragmentManager().beginTransaction()
		.add(R.id.linearLayoutRoot, setFixedScheduleFragment).commit();
		new GetMySchedule().execute(getIntent().getExtras().getString("myFBID"));
	}

	private void findView() {
		buttonPrevious = (Button) findViewById(R.id.buttonPrevious);
		buttonDone = (Button) findViewById(R.id.buttonDone);
	}
	
	private void setListenerOrAdapter() {
		buttonPrevious.setOnClickListener(new ButtonPreviousClick());
		buttonDone.setOnClickListener(new ButtonDoneClick());
	}
	
	private class ButtonPreviousClick implements Button.OnClickListener {

		@Override
		public void onClick(View v) {
			SetFixedScheduleActivity.this.finish();
		}
	}
	
	private class ButtonDoneClick implements Button.OnClickListener {

		@Override
		public void onClick(View v) {
			new PostModifySchedule().execute(getIntent().getExtras().getString("myFBID"));
		}
		
		private class PostModifySchedule extends AsyncTask<String, Void, Void> {
			private ProgressDialog proDialog;
			
			@Override
			protected void onPreExecute() {
				proDialog = ProgressDialog.show(SetFixedScheduleActivity.this, "設定行程表中",
						"正在設定您的行程表...");
				proDialog.setCancelable(false);
			}

			@Override
			protected Void doInBackground(String... params) {
				try {
					JSONObject jsonObj = new JSONObject();
					JSONArray informsJsonArr = new JSONArray();
					
					jsonObj.put("id", params[0]);
					for (CalendarTextData itData: setFixedScheduleFragment.getCalendarTextDataSet()) {
						JSONObject informJsonObj = new JSONObject();
						
						informJsonObj.put("day", itData.getDay());
						informJsonObj.put("startHour", itData.getStartHour());
						informJsonObj.put("startMinute", itData.getStartMinute());
						informJsonObj.put("overHour", itData.getOverHour());
						informJsonObj.put("overMinute", itData.getOverMinute());
						informJsonObj.put("title", itData.getTitle());
						informJsonObj.put("ps", itData.getPs());
						informJsonObj.put("priority", itData.getPriority());
						informsJsonArr.put(informJsonObj);
					}
					jsonObj.put("informs", informsJsonArr);
					HttpHelper.executePost("http://iculture.twgg.org/schedule/modifySchedule.php",
							jsonObj.toString());
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				}
				return null;
			}
			
			@Override
			protected void onPostExecute(Void result) {
				proDialog.cancel();
				new AlertDialog.Builder(SetFixedScheduleActivity.this)
				.setTitle("設定完成")
				.setMessage("行程表設定完成")
				.setPositiveButton("確定", new FinishDialogPositiveButtonClick())
				.setCancelable(false)
				.show();
			}
			
			private class FinishDialogPositiveButtonClick implements DialogInterface.OnClickListener {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					SetFixedScheduleActivity.this.finish();
				}
			}
		}
	}
	
	private class GetMySchedule extends GetMyScheduleHelper {
		private ProgressDialog proDialog;
		
		@Override
		protected void onPreExecute() {
			proDialog = ProgressDialog.show(SetFixedScheduleActivity.this, "取得行程表", "正在取得行程表...");
			proDialog.setCancelable(false);
		}

		@Override
		protected void onPostExecute(String jsonString) {
			try {
				JSONArray respJsonArr = new JSONArray(jsonString);
				
				for (int i=0; i<respJsonArr.length(); i++) {
					CalendarTextData data = CalendarTextDataFactory.newByJsonObject(respJsonArr.getJSONObject(i));
					
					setFixedScheduleFragment.addCalendarText(data, new CalendarTextClick(data),
							new CalendarTextLongClick(data), Gravity.LEFT);
				}
				proDialog.cancel();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	protected void onActivityResult(int reqCode, int resultCode, Intent data) {
		super.onActivityResult(reqCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			List<Integer> dayList = bundle.getIntegerArrayList("dayList");
			int startHour = bundle.getBundle("startTime").getInt("hour");
			int startMinute = bundle.getBundle("startTime").getInt("minute");
			int overHour = bundle.getBundle("overTime").getInt("hour");
			int overMinute = bundle.getBundle("overTime").getInt("minute");
			int priority = bundle.getInt("priority");
			String title = bundle.getString("title");
			String ps = bundle.getString("ps");
			
			switch (reqCode) {
				case SET_SCHEDULE_REQUEST_CODE:
					addCalendarTextDatas(dayList, startHour, startMinute, overHour, overMinute, priority,
							title, ps);
					break;
				case MODIFY_SCHEDULE_REQUEST_CODE:
					setFixedScheduleFragment.removeCalendarText(bundle.getInt("id"));
					addCalendarTextDatas(dayList, startHour, startMinute, overHour, overMinute, priority,
							title, ps);
			}
		}
	}
	
	private void addCalendarTextDatas(List<Integer> dayList, int startHour, int startMinute,
			int overHour, int overMinute, int priority, String title, String ps) {
		for (int day: dayList) {
			CalendarTextData calTextData = new CalendarTextData(day, startHour,
					startMinute, overHour, overMinute, priority, title, ps);
			
			setFixedScheduleFragment.addCalendarText(calTextData, new CalendarTextClick(calTextData),
					new CalendarTextLongClick(calTextData), Gravity.CENTER_HORIZONTAL);
		}
	}

	private class CalendarTextClick implements TextView.OnClickListener {
		private CalendarTextData calTextData;
		
		private CalendarTextClick(CalendarTextData calTextData) {
			this.calTextData = calTextData;
		}

		@Override
		public void onClick(View arg0) {
			Bundle bundle = new Bundle();
			Intent intent = new Intent(SetFixedScheduleActivity.this, SetScheduleActivity.class);
			
			bundle.putParcelable("data", calTextData);
			bundle.putInt("setType", 1);
			intent.putExtras(bundle);
			startActivityForResult(intent, MODIFY_SCHEDULE_REQUEST_CODE);
		}
	}
	
	private class CalendarTextLongClick implements TextView.OnLongClickListener {
		private CalendarTextData calTextData;
		
		private CalendarTextLongClick(CalendarTextData calTextData) {
			this.calTextData = calTextData;
		}

		@Override
		public boolean onLongClick(View v) {
			new AlertDialog.Builder(SetFixedScheduleActivity.this)
			.setTitle("刪除行程")
			.setMessage("請問您要刪除此行程嗎?")
			.setNegativeButton("不要", null)
			.setPositiveButton("好", new DialogPositiveClick())
			.show();
			return false;
		}
		
		private class DialogPositiveClick implements DialogInterface.OnClickListener {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				setFixedScheduleFragment.removeCalendarText(calTextData.getId());
			}
		}
	}
}
